<template>
  <div>
    <el-container>
      <el-header>
        <el-button type="primary" plain @click="insertEmailWrite">发送</el-button>
        <el-button type="primary" plain @click="saveAsDraft">存草稿</el-button>
      </el-header>

      <el-main>
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="80px"
          :label-position="labelPosition">
          <!-- recipients -->
          <el-form-item label="收件人" prop="recipientsId">
            <el-select v-model="formData.recipientsId" placeholder="请选择收件人" :style="{ width: '100%' }">
              <el-option v-for="user in userList" :key="user.userId" :label="`${user.userName} (${user.email})`"
                :value="user.userId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="主题" prop="project">
            <el-input v-model="formData.project" placeholder="请输入主题" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>

          <el-form-item label="类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择类型" clearable filterable :style="{ width: '100%' }">
              <el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="附件" prop="address">
            <file-upload v-model="formData.address" />
          </el-form-item>

          <el-form-item label="正文" prop="content">
            <el-input v-model="formData.content" type="textarea" placeholder="请输入" :maxlength="255"
              :autosize="{ minRows: 8, maxRows: 8 }" :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { listUser } from '@/api/system/user';
import { saveAsDraft, insertEmailWrite } from '@/api/email/write';
export default {
  data() {
    return {
      // 文件上传
      fileList: [
        { name: '', url: '' }
      ],
      userList: [],
      deptList: [],
      labelPosition: 'left',
      formData: {
        recipientsId: '',
        project: '',
        type: '',
        content: '',
        deptId: '',
        address: null,
      },
      rules: {
        recipientsId: [
          { required: true, message: '请选择收件人', trigger: 'change' }
        ],
        project: [
          { required: true, message: '请输入主题', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择邮件类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      uploadAction: 'https://jsonplaceholder.typicode.com/posts/',
      uploadfileList: [],
      typeOptions: [
        { label: '普通邮件', value: 0 },
        { label: '机密邮件', value: 1 }
      ]
    }
  },
  created() {
    this.getUserList();

    //
    if (this.$route.query.recipientsId != undefined) {
      this.formData = this.$route.query;
      this.formData.recipientsId = parseInt(this.formData.recipientsId)
      this.formData.type = parseInt(this.formData.type)
    }
  },
  methods: {
    // 文件上传
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 表单重置
    reset() {
      this.formData = {
        recipientsId: null,
        project: null,
        type: '',
        upload: null,
        content: null,
        deptId: null
      };
      this.resetForm("form");
    },
    // 点击存为草稿，发送一个请求向后端，草稿类型为0，在sql语句当中 邮件类型symbol为0
    // 点击存为草稿以后应该清空下面的内容
    saveAsDraft() {
      saveAsDraft(this.formData).then((result) => {
        if (this.formData.recipientsId == null || this.formData.project == null || !this.formData.type == null || !this.formData.content == null) {
          this.$message.error('请填写所有必填项！');
          return;
        } else {
          if (result.code == 200) {
            this.$message.success(result.msg);
            this.reset();
          } else {
            this.$message.error(result.msg);
          }
        }
      }
      );
    },

    // 新增写信方法
    insertEmailWrite() {
      insertEmailWrite(this.formData).then((result) => {
        if (this.formData.recipientsId == null || this.formData.project == null || !this.formData.type == null || !this.formData.content == null) {
          this.$message.error('请填写所有必填项！');
          return;
        } else {
          if (result.code == 200) {
            this.$message.success(result.msg);
            this.reset();
          } else {
            this.$message.error(result.msg);
          }
        }
      }
      );
    },
    // 获取用户邮箱初始化在页面当中
    getUserList() {
      listUser().then((result) => {
        this.userList = result.rows;
      });
    },
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        // TODO 提交表单  
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    uploadBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    }
  }
}  
</script>